import Vue from 'vue'
import Vuex from 'vuex'
import {getToken,setToken,removeToken} from '@/utils/auth'
import {login,logout,info,register} from '@/api/account'
Vue.use(Vuex)

export default new Vuex.Store({
    state:{
        token:getToken(),
        user:{
            name:'',
            phoneNumber:''
        },
    },
    mutations:{
        SET_TOEKN:(state,token)=>{
            state.token=token
        },
        SET_USER:(state,user)=>{
            state.user=user
        }
    },
    actions:{
        //用户登录
        login({commit},userInfo){
            const {user,password}=userInfo
            return new Promise((resolve,reject)=>{
                login({phonenumber:user,password:password}).then((response)=>{
                    const {data}=response
                    commit('SET_TOKEN',data.access_token)
                    setToken(data.access_token)
                    resolve()
                }).catch((error)=>{
                    reject(error)
                })
            })
        },
        //用户注册
        register({commit},userInfo){
            return new Promise((resolve,reject)=>{
                register(userInfo).then((response)=>{
                    const {data}=response
                    commit('SET_TOKEN',data.access_token)
                    setToken(data.access_token)
                    resolve()
                }).catch((error)=>{
                    reject(error)
                })
            })
        },
        //用户信息
        getInfo({commit}){
            return new Promise((resolve,reject)=>{
                info().then((response)=>{
                    const {data}=response
                    if(!data){
                        reject('token验证失败，请重新登录')
                    }
                     commit('SET_USER',data)
                     resolve(data)
                }).catch((error)=>{
                    reject(error)
                })
            })
        },
        //用户退出
        logout({commit,state}){
            return new Promise((resolve,reject)=>{
                logout(state.token).then(()=>{
                    commit('SET_TOKEN','')
                    removeToken()
                    resolve()
                }).catch((error)=>{
                    reject(error)
                })
            })
        },
        //移除token
        resetToken({commit}){
            return new Promise(resolve=>{
                commit('SET_TOKEN','')
                removeToken()
                resolve()
            })
        }
    }
})